package com.torry.workflow.service.user.facade;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.torry.workflow.api.user.api.OrgApi;
import com.torry.workflow.api.user.entity.*;
import com.torry.workflow.common.exception.BizException;
import com.torry.workflow.service.user.service.*;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@DubboService
@Component
public class OrgFacade implements OrgApi {
    @Resource
    private IOrgService iOrgService;
    @Resource
    private IRoleOrgService iRoleOrgService;
    @Resource
    private IUserService iUserService;

    @Override
    @Transactional
    public void saveOrg(Org org) {
        if (orgIsExist(org)) {
            throw new BizException(400, "该组织架构下已有相同部门");
        }
        iOrgService.saveOrUpdate(org);

    }

    private boolean orgIsExist(Org org) {
        Integer pid = org.getPid();
        Org orgInfo = iOrgService.getOne(new QueryWrapper<Org>()
                .eq("deleted", 0)
                .eq("name", org.getName())
                .eq(pid != null, "pid", pid).isNull(pid == null, "pid"));
        if (org.getId() == null) {
            return orgInfo != null;
        }
        return orgInfo != null && !orgInfo.getId().equals(org.getId());
    }

    @Override
    public List<Org> getOrgTree() {
        /*List<Org> parents = iOrgService.list(new QueryWrapper<Org>().eq("deleted", 0).isNull("pid"));
        return setChildren(parents);*/
        return iOrgService.getOrgTree();
    }

    private List<Org> setChildren(List<Org> parents) {
        parents.forEach(org -> {

            List<Org> list = iOrgService.list(new QueryWrapper<Org>().eq("deleted", 0).eq("pid", org.getId()));
            if (CollectionUtils.isNotEmpty(list)) {
                setChildren(list);
                org.setChildren(list);
            }
        });
        return parents;
    }

    @Override
    public void deleteOrgByIds(List<Integer> ids) {
        // 移除组织架构
        iOrgService.update(new UpdateWrapper<Org>().set("deleted", 1).in("id", ids));
        // 移除角色下所配置的该组织
        iRoleOrgService.update(new UpdateWrapper<RoleOrg>().set("deleted", 1).in("org_id", ids));
        // 将该部门下的用户，部门置为空
        iUserService.update(new UpdateWrapper<User>().set("org_id", null).eq("deleted", 0).in("org_id", ids));
    }

    @Override
    public List<Org> getOrgTreeWithUser() {
        List<Org> parents = iOrgService.list(new QueryWrapper<Org>().eq("deleted", 0).isNull("pid"));
        return setChildren(parents);
    }
}
